<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '采购信息' },
          { name: 'box-dtl', title: '采购明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <div id="box-base" class="box-title">采购信息</div>
          <customFormItem
            label="采购单号"
            name="busKey"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.staticHtml.name"
            :config="{defaultValue: '自动获取'}"
          />

          <customFormItem
            label="收货仓库" name="warehouseName" :parent="_self" :form="form"
            @focusTo="$refs.warehouseName.focus()"
            :type="constCommon.formItemType.slot.name"
          >
            <template #content>
              <warehouseSelect
                :flagCenter="true"
                v-model="form.warehouseId"
                :valueDisplay="form.warehouseName"
                @change="warehouseChange"
                ref="warehouseName"
                :disabled="propReadonly"
              />
            </template>
          </customFormItem>

          <customFormItem
            label="采购科室" name="deptName" :parent="_self" :form="form"
            @focusTo="$refs.deptName.focus()"
            :type="constCommon.formItemType.slot.name"
          >
            <template #content>
              <deptSelect
                v-model="form.deptId"
                :valueDisplay="form.deptName"
                @change="deptIdChange"
                ref="deptName"
                :disabled="propReadonly"
              />
            </template>
          </customFormItem>

          <customFormItem
            label="需求科室" name="deptNameDemand" :parent="_self" :form="form"
            @focusTo="$refs.deptNameDemand.focus()"
            :type="constCommon.formItemType.slot.name"
          >
            <template #content>
              <deptSelect
                v-model="form.deptIdDemand"
                :valueDisplay="form.deptNameDemand"
                @change="selectDemandDept"
                ref="deptNameDemand"
                :disabled="propReadonly"
              />
            </template>
          </customFormItem>

          <customFormItem
            label="采购人"
            name="busUser"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.staticHtml.name"
            :config="{defaultValue: '自动获取'}"
          />

          <customFormItem
            label="采购日期"
            name="busDate"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.datePicker.name"
            :config="{defaultValue: '自动获取'}"
            disabled
          />

          <customFormItem
            label="到货日期"
            name="dateLates"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.datePicker.name"
          />


          <customFormItem
            label="供应商" name="supplierName" :parent="_self" :form="form"
            help-tip="有明细数据时不可编辑"
            @focusTo="$refs.supplierName.focus()"
            :type="constCommon.formItemType.slot.name"
            :disabled="cpHasCountDtl"
          >
            <template #content>
              <spSelect
                v-model="form.supplierId"
                :valueDisplay="form.supplierName"
                @change="selectSupplier"
                :disabled="cpHasCountDtl || propReadonly"
                ref="supplierName"
              />
            </template>
          </customFormItem>

          <customFormItem label="订单类型" name="poType" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.purchaseOrderType}"
                          help="有明细数据时不可编辑"
                          :disabled="cpHasCountDtl"
          />
          <customFormItem label="采购分类" name="purchaseType" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.baseMatrType}"
                          help="有明细数据时不可编辑"
                          :disabled="cpHasCountDtl"
          />
          <customFormItem label="标签管理" name="flagOmoc" :parent="_self" :form="form"
                          :type="constCommon.formItemType.radio.name"
                          :config="{options: constCommon.nobusConst.yesNoBoolean}"
                          help="有明细数据时不可编辑"
                          :disabled="cpHasCountDtl"
          />

          <customFormItem label="存储温度" name="temperature" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.matrTemperature}"
                          v-show="cpIsReagent"
          />

          <customFormItem
            label="订单金额"
            name="amount"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.inputNumber.name"
            :config="{defaultValue: 0}"
            disabled
          />
          <customFormItem
            label="备注"
            name="remark"
            :parent="_self"
            :form="form"
          />

        </template>
      </customForm>

      <div id="box-dtl" class="box-title">采购明细</div>
      <data-view
        propViewKey="purchase_order_item"
        propViewForm="purchase/order-item/detail.vue"
        :propInitData="form"
        ref="childDataView"
        :propHideFlowSelect="true"
        :propAutoFetchData="false"
        @edit-input="editInput"
        :propFlowKey="propParent.propFlowKey"
        class="data-view-inlinebtn"
        :propParentPage="_self"
        @customSelectFocus="customSelectFocus"
        @afterTableDataChange="afterTableDataChange"
        :propNoEditRow="true"
        :propBeforeClick="propBeforeClickDtl"
      >
      </data-view>
    </div>
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'
import warehouseSelect from '@/components/custom/bus/select/warehouseSelect.vue'
import deptSelect from '@/components/custom/bus/select/deptSelect.vue'
import spSelect from '@/components/custom/bus/select/spSelect.vue'

export default {
  data() {
    return {
      form: {},
      viewData: {},
      supplierSelectColumns: [
        {label: '名称', name: 'name', width: 300, search: true},
        {label: '助记码', name: 'namePy', width: 80, search: true}
      ],
      currentRow: {},
      selectMatrColumns: [
        {title: '供应商名称', field: 'supplierName', width: 250, search: true},
        {title: '品名', field: 'name', width: 180, search: true},
        {title: '品规', field: 'spec', width: 150, search: true},
        {title: '厂商名称', field: 'mfgName', search: true},
        {title: '单品单位', field: 'skuUnit', width: 80, search: false},
        {title: '单品单价', field: 'skuPrice', width: 80, search: false},
      ]
    }
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propParentPage: Object
  },
  components: {
    customAnchor,
    warehouseSelect,
    deptSelect,
    spSelect,
  },
  computed: {
    // 是否是试剂
    cpIsReagent() {
      return this.form.purchaseType && this.form.purchaseType == this.constCommon.dictType.baseMatrTypeReagent
    },
    // 是否有明细
    cpHasCountDtl() {
      if (!this.form.countDtl) {
        return false
      }
      return this.form.countDtl > 0
    }
  },
  methods: {
    // 科室选择
    deptIdChange(item) {
      this.$set(this.form, 'deptId', item.id)
      this.$set(this.form, 'deptName', item.name)
    },
    //行编辑普通input框的修改事件，比如修改耗材包的数量后自动更新基本单位的数量
    editInput({row, column}) {
      if (column.property == 'packageQty') {
        if (!row.packageRate) { //如果没有换算比，先计算,column.model.value保存了原值
          this.$set(row, 'packageRate', column.model.value / row.skuQty)
        }
        this.$set(row, 'skuQty', row.packageRate * row.packageQty)
        this.$set(row, 'amount', this.utilNum.toFixed(row.skuPrice * row.skuQty))
      }
    },

    // 加载明细
    loadDtl() {
      let wrapper = this.$newWrapper()
      if (this.form.id) {
        wrapper.eq('orderId', this.form.id)
      } else {
        wrapper.ne(1, 1)
      }
      this.$refs.childDataView.setQueryWrapper(wrapper)
    },
    //选择供应商事件
    selectSupplier(row) {
      this.$set(this.form, 'supplierId', row.id)
      this.$set(this.form, 'supplierName', row.name)
    },
    // 选择需求科室
    selectDemandDept(row) {
      this.$set(this.form, 'deptIdDemand', row.id)
      this.$set(this.form, 'deptNameDemand', row.name)
    },
     // 选择仓库
    warehouseChange(row) {
      this.$set(this.form, 'warehouseId', row.id)
      this.$set(this.form, 'warehouseName', row.name)
    },
    //获取临采耗材入库次数
    getTemporarPurchase() {
      // let ids = []
      // ids = this.getChildRows().filter(matr => matr.flagTemporaryPurchase == 1).map(matr => matr.matrId)
      // if (ids.length == 0) {
      //   return
      // }
      // this.$ajax.post('/purchase/order/getNum', ids).then(res => {
      //   if (res.data != null || res.data.length > 0) {
      //     this.$nextTick(() => {
      //       this.$confirm(res.msg + '。 是否将耗材修改为正常耗材', '提示', {
      //         confirmButtonText: '确定',
      //         cancelButtonText: '取消',
      //         type: 'warning'
      //       }).then(() => {
      //         this.$ajax.post('/base/matr/updateTemporaryPurchase', res.data).then(resp => {
      //           if (resp.code == 0) {
      //             this.utilMessage.success('修改成功')
      //           }
      //         })
      //       }).catch(() => {
      //         this.utilMessage.info('已取消修改')
      //       })
      //     })
      //   }
      // })
    },
    // 自定义选择聚焦回调
    customSelectFocus(column, row) {
      // 包装名称
      if (column.name == 'packageUnit') {
        if (this.strings.isBlank(row.matrId)) {
          this.utilMessage.warning('请先选择商品')
          return
        }
        this.utilSelect.matrUnit(this.packageUnitSelect, row.matrId, null, true)
      }
    },
    // 商品选择后
    matrSelect(rows, refName) {
      let rowFirst = rows[0]
      let matrIdList = rows.filter(
        item => item.matrId != rowFirst.matrId
          && item.matrBaseType == rowFirst.matrBaseType
          && item.flagOmoc == rowFirst.flagOmoc
          && item.flagConsignment == rowFirst.flagConsignment
          && item.supplierId == rowFirst.supplierId
      ).map(itemNew => {
        return itemNew.matrId
      })
      matrIdList.push(rowFirst.matrId)
      if (rows.length != matrIdList.length) {
        this.utilMessage.confirm(`所选择的数据中，有${rows.length - matrIdList.length}条属性不一致，已忽略。是否提交?`, () => {
          //主单据未保存
          if(this.propParent.cpFormNew) {
            this.setFormByDtl(rowFirst)
            this.propParent.ocAsynSaveViewForm(() => {
              this.saveBatchItem(matrIdList, true)
            })
          }
        })
        return
      }

      //主单据未保存
      if(this.propParent.cpFormNew) {
        this.setFormByDtl(rowFirst)
        this.propParent.ocAsynSaveViewForm(() => {
          this.saveBatchItem(matrIdList)
        })
        return
      }
      this.saveBatchItem(matrIdList)
    },
    // 商品选择后
    saveBatchItem(matrIdList) {
      this.utilVue.loadShow(true)

      let param = {matrIdList: matrIdList, orderId: this.form.id}
      this.$ajax.post('/purchase/order_item/saveBatchMatr', param).then((resp) => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.form.countDtl = matrIdList.length
          this.loadDtl()
          this.afterTableDataChange()
        }
      })
    },
    // 单位选择后
    packageUnitSelect(row, refName) {
      // 当前选中行
      let currentRow = this.$refs.childDataView.getCurrentRow()
      //换算单位后是否为整数
      if (this.utilNum.isInt(currentRow.skuQty / row.rate)) {
        this.$set(currentRow, 'packageUnit', row.unit)
        this.$set(currentRow, 'packageRate', row.rate)
        this.$set(currentRow, 'packageQty', currentRow.skuQty / row.rate)
        this.$set(currentRow, 'amount', currentRow.skuPrice * currentRow.skuQty)
      } else  {
        this.utilMessage.confirm('该入库明细选择的包装不是整数,需要自动拆分吗', () => {
          this.$set(currentRow, 'packageUnit', row.unit)
          this.$set(currentRow, 'packageRate', row.rate)
          this.$set(currentRow, 'packageQty', currentRow.skuQty / row.rate)
          this.$set(currentRow, 'amount', currentRow.skuPrice * currentRow.skuQty)
          this.splitOrderItem(currentRow)
        })
      }
    },

    // 明细 新增、删除、修改后调用
    afterTableDataChange() {
      this.utils.refreshRefs(this)
    },
    // 根据明细设置表单属性
    setFormByDtl(dtl) {
      this.$set(this.form, 'purchaseType', dtl.matrBaseType)
      this.$set(this.form, 'flagOmoc', dtl.flagOmoc)
      this.$set(this.form, 'poType', dtl.flagConsignment ? this.constCommon.dictType.purchaseOrderTypeC : this.constCommon.dictType.purchaseOrderTypeB)
      this.$set(this.form, 'flagConsignment', dtl.flagConsignment)
      this.$set(this.form, 'supplierId', dtl.supplierId)
      this.$set(this.form, 'supplierName', dtl.supplierName)
    },
    // 列表添加按钮
    propBeforeClickDtl(button, formData , rowData, that) {
      //列表添加按钮 其他入库
      if (button.key == 'vb-add') {
        let poType = this.form.poType
        let flagConsignment = ''
        if (poType) {
          flagConsignment = poType.toUpperCase() == this.constCommon.dictType.purchaseOrderTypeC
        }
        this.utilSelect.matrMore(
          this.matrSelect,
          {
            warehouseIdStock: this.form.warehouseId
          },
          this.form.supplierId,
          this.form.purchaseType,
          flagConsignment,
          this.form.flagOmoc
        )
        return false
      }


      return true;
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        if (!this.form.id) {
          if (this.strings.isNotBlank(this.utils.getCurrentWarehouse().warehouseId)) {
            this.$set(this.form, 'warehouseId', this.utils.getCurrentWarehouse().warehouseId)
            this.$set(this.form, 'warehouseName', this.utils.getCurrentWarehouse().warehouseName)
          }
          //需求科室和采购科室为当前科室
          let CurrentUser = this.utils.getCurrentUser()
          this.$set(this.form, 'deptIdDemand', CurrentUser.deptId)
          this.$set(this.form, 'deptNameDemand', CurrentUser.deptName)
          this.$set(this.form, 'deptId', CurrentUser.deptId)
          this.$set(this.form, 'deptName', CurrentUser.deptName)

          this.$set(this.form, 'busUser', this.utils.getCurrentUser().name)
          this.$set(this.form, 'busDate', new Date().format(this.dates.defaultDatePattern))
          this.$set(this.form, 'temperature',  '无')
          this.$set(this.form, 'dateLates', this.dates.getDateAfterDays(3))
        }
        that.loadDtl()
      },
      afterSave: () => {

      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow:  (valueTO, button) => {
        if (!that.cpHasCountDtl) {
          this.utilMessage.error('订单明细为空，不允许提交')
          return false
        }
        if (button.flagEnd) {
          this.getTemporarPurchase()
        }
        return true
      },
      afterFlow: (flowButtonKey) => {
        return true
      },
      async afterClick(button, data, viewForm) {
        let {key: buttonKey} = button
        if (buttonKey === 'printOrderQr') {
          that.utilVue.loadShow(true)
          that.$ajax.get(`/purchase/order/printOrderQRCode?orderId=${viewForm.form.id}`,
            {}).then(response => {
            that.utilVue.loadHide()
            console.log('response.data', response.data)
            if (response.code == 0 && response.data) {
              let param = {
                'that': that, //当前调用对象
                configList: [ //打印配置，可以多个
                  {
                    //打印配置
                    printBusType: 'purchaseOrder', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                    //主单据数据或者数据查询配置
                    formData: that.form, //数据对象
                    formDataId: that.form.id,
                    barCodeInfo: response.data.items,
                    flagCodeInfo: true,
                  }
                ]
              }
              global.utilPrint.openFormPrint(param)
            }
          })
        } else if (buttonKey === 'printOrder') {
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'purchaseOrder', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        }
      },
      beforeClose: () => {
        return true
      }
    })
  }
}
</script>
